package com.hong.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author: csh
 * @Date: 2021/4/7 14:22
 * @Description:生产者
 */
public class Producer {

    private final static String QUEUE_NAME = "rabbitmq-hong";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        //mq地址
        factory.setHost("localhost");
        //获取连接
        try (Connection connection = factory.newConnection();
            //创建通道
            Channel channel = connection.createChannel()) {

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            int i = 0;
            while (true){
                i++;
                //消息
                String message = "Hello hong!"+i;
                //发布消息
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
                System.out.println(" [x] Sent '" + message + "'");
                Thread.sleep(3000);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
